package com.tsing.common.exceptions;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;

@Component
public class ExceptionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (ServletException e) {
            // 异常捕获，发送到error controller
            Throwable rootCause = e.getRootCause();
            if (rootCause instanceof BusinessException) {
                BusinessException be = (BusinessException) rootCause;
                request.setAttribute("filter.error", be);
            } else if (rootCause instanceof IllegalArgumentException) {
                IllegalArgumentException be = (IllegalArgumentException) rootCause;
                request.setAttribute("filter.error", be);
            }
            //将异常分发到/error/exthrow控制器
            request.getRequestDispatcher("/error/exthrow").forward(request, response);
        }
    }

}
